package com.example.spring.demo.common.model.vo;

import com.example.spring.demo.entity.SysMenu;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class MakeMenuTree { //菜单树
    //递归组装菜单树
    public static List<SysMenu> makeTree(List<SysMenu> menuList, Long pid) {
        //接收组装后的树数据
        List<SysMenu> list = new ArrayList<>();
        //判断menuList是否为空，如果为空，直接返回空的数据
        Optional.ofNullable(menuList).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null && item.getParentId().equals(pid))
                .forEach(item -> {
                    //组装树数据
                    SysMenu menu = new SysMenu();
                    //快速复制值
                    BeanUtils.copyProperties(item, menu);
                    //设置
                    menu.setLabel(item.getTitle());
                    menu.setValue(item.getMenuId());
                    //递归查找下级,自己调用自己
                    List<SysMenu> children = makeTree(menuList, item.getMenuId());
                    menu.setChildren(children);
                    list.add(menu);
                });
        return list;
    }

    //构造路由数据
    public static List<MenuVo> makeRouter(List<SysMenu> menuList, Long pid) {
        //构建存放路由数据的容器
        List<MenuVo> list = new ArrayList<>();
        Optional.ofNullable(menuList).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null && item.getParentId().equals(pid))
                .forEach(item -> {
                    MenuVo router = new MenuVo();
                    router.setMenuId(item.getMenuId());
                    router.setIcon(item.getIcon());
                    router.setTitle(item.getTitle());
                    router.setPath(item.getPath());

                    //设置children 递归调用：自己调用自己
                    List<MenuVo> children = makeRouter(menuList, item.getMenuId());
                    router.setChildren(children);
                    list.add(router);
                });
        return list;
    }
}
